package com.logic.modular.gameCore.cultivate.prop;

import com.baomidou.mybatisplus.extension.service.IService;
import com.comment.pojo.domain.logic.core.CoreProp;
import com.comment.dubbo.service.CorePropServiceClient;
import com.logic.modular.gameCore.cultivate.prop.mapper.CorePropMapper;
import lombok.extern.slf4j.Slf4j;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;


/**
 * 道具表(CoreProp)表服务实现类
 *
 * @author cxy
 * @since 2024-08-05 18:15:26
 */
@Slf4j
@Service
@DubboService(interfaceClass = CorePropServiceClient.class)
public class CorePropServiceImpl extends ServiceImpl<CorePropMapper, CoreProp>
        implements IService<CoreProp>, CorePropServiceClient {
    private static final Cache<String, Map<Long, CoreProp>> cache = Caffeine.newBuilder().build();

    @PostConstruct
    private void init() {
        CoreProp initSelect = CoreProp.builder().build();
        List<CoreProp> list = this.list(new LambdaQueryWrapper<>(initSelect));
        log.info("开始缓存道具表数据,数据量为:{}", list.size());
        cache.put(
                "coreProp",
                list.stream().collect(Collectors.toMap(CoreProp::getId, CoreProp -> CoreProp))
        );
        log.info("道具表数据缓存完成");
    }

    public static List<CoreProp> listCache() {
        Map<Long, CoreProp> values = mapCache();
        return new ArrayList<>(values.values());
    }

    @Override
    public Map<Long, CoreProp> map() {
        return mapCache();
    }

    public static Map<Long, CoreProp> mapCache() {
        Map<Long, CoreProp> values = cache.getIfPresent("coreProp");
        if (Objects.isNull(values)) {
            throw new RuntimeException("道具表数据为空");
        }
        return values;
    }

    public static CoreProp getCache(Long id) {
        Map<Long, CoreProp> values = mapCache();
        return values.get(id);
    }
}
